#include <QRegularExpression> //正则表达式
#include <QJsonDocument>
#include <QDebug>

#include "registerdialog.h"
#include "ui_registerdialog.h"
#include "global.h"
#include "httpmgr.h"
#include "singleton.h"

RegisterDialog::RegisterDialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::RegisterDialog)
, _countdown(5)
{
    ui->setupUi(this);

    _SetWidgetState();
    _SetConnect();
    _InitHttpHandlers();

    ui->error_tipe_label->clear();
}

void RegisterDialog::_SetWidgetState()
{
    //设置输入模式为密码模式
    ui->pass_edit->setEchoMode(QLineEdit::Password);
    ui->confirm_edit->setEchoMode(QLineEdit::Password);

    //设置错误显示控件的初始状态，用于qss的状态切换
    ui->error_tipe_label->setProperty("state", "normal");
    repolish(ui->error_tipe_label);

    //设置鼠标移动到label上的的图标
    // ui->pass_label_2->setCursor(Qt::PointingHandCursor);
    // ui->confirm_label_2->setCursor(Qt::PointingHandCursor);

    //设置标签的状态类型
    ui->pass_label_2->SetState("unvisible","unvisible_hover","","visible",
                               "visible_hover","");
    ui->confirm_label_2->SetState("unvisible","unvisible_hover","","visible",
                                  "visible_hover","");

    //创建返回登录定时器
    _countdown_timer = new QTimer(this);
}


void RegisterDialog::_SetConnect()
{
    //http 注册消息信号和槽
    connect(MagicSingleton<HttpMgr>::GetInstance().get(), &HttpMgr::sig_reg_mod_finish,
            this, &RegisterDialog::slot_reg_mod_finish);

    // 输入框错误检测
    connect(ui->user_edit,&QLineEdit::editingFinished,this,[this](){
        _CheckUserValid();
    });
    connect(ui->email_edit, &QLineEdit::editingFinished, this, [this](){
        _CheckEmailValid();
    });
    connect(ui->pass_edit, &QLineEdit::editingFinished, this, [this](){
        _CheckPassValid();
    });
    connect(ui->confirm_edit, &QLineEdit::editingFinished, this, [this](){
        _CheckConfirmValid();
    });
    connect(ui->varify_edit, &QLineEdit::editingFinished, this, [this](){
        _CheckVarifyValid();
    });

    //切换密码显示状态
    connect(ui->pass_label_2, &ClickedLabel::clicked, this, [this]() {
        auto state = ui->pass_label_2->GetCurState();
        if(state == ClickLbState::Normal){
            ui->pass_edit->setEchoMode(QLineEdit::Password);
        }else{
            ui->pass_edit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
    });
    connect(ui->confirm_label_2, &ClickedLabel::clicked, this, [this]() {
        auto state = ui->confirm_label_2->GetCurState();
        if(state == ClickLbState::Normal){
            ui->confirm_edit->setEchoMode(QLineEdit::Password);
        }else{
            ui->confirm_edit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
    });

    //创建返回登录定时器槽函数
    connect(_countdown_timer, &QTimer::timeout, this, [this](){
        if(_countdown == 0)
        {
            _countdown = 5;
            _countdown_timer->stop();
            //发送信号切换回登录界面
            emit sigSwitchLogin();
            return;
        }
        --_countdown;
        auto str = QString("注册成功，%1 s 后返回登录").arg(_countdown);
        ui->timer_label->setText(str);
    });
}


void RegisterDialog::_ShowTip(QString str, bool ok)
{
    ui->error_tipe_label->setText(str);
    if(ok)
    {
        ui->error_tipe_label->setProperty("state", "normal");
    }
    else
    {
        ui->error_tipe_label->setProperty("state", "err");
    }

    //根据 qss 文件刷新控件样式
    repolish(ui->error_tipe_label);
}


//初始化 ReqId 对应的回调函数
void RegisterDialog::_InitHttpHandlers()
{
    //祖册获取验证码回调函数
    this->_handlers.insert(ReqId::ID_GET_VARIFY_CODE, [this](const QJsonObject& json_obj){
        int error = json_obj["code"].toInt();
        if(error != ErrorCode::SUCCESS)
        {
            _ShowTip(tr("json 参数错误"), false);
            qDebug() << "error message: " << json_obj["msg"].toString();
            return;
        }

        auto email = json_obj["email"].toString();
        _ShowTip(tr("验证码已发送到邮箱，注意查收"), true);
        qDebug() << __FILE__ << ":" << __LINE__ << " email is: " << email;
    });

    this->_handlers.insert(ReqId::ID_REG_USER, [this](const QJsonObject& json_obj){
        qDebug()<< "=================";
        int error = json_obj["code"].toInt();
        if(error != ErrorCode::SUCCESS){
            _ShowTip(tr("参数错误"),false);
            return;
        }
        // auto email = json_obj["email"].toString();
        _ShowTip(tr("用户注册成功"), true);
        _ChangeTipPage();
        // qDebug()<< "email is " << email ;
    });
}

RegisterDialog::~RegisterDialog()
{
    qDebug() <<"~RegisterDialog run";
    delete ui;
}

//获取验证码按钮槽函数
void RegisterDialog::on_get_code_btn_clicked()
{
    auto email = ui->email_edit->text();
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)(\.(\w+))+)");
    if(!regex.match(email).hasMatch())
    {
        _ShowTip(tr("邮箱格式不正确"), false);
        return;
    }

    //请求验证码
    QJsonObject send_json;
    send_json["email"] = email;
    auto url = QUrl(gate_url_prefix + "/get_verification_code");
    MagicSingleton<HttpMgr>::GetInstance()->PostHttpReq(url, send_json, ReqId::ID_GET_VARIFY_CODE, Modules::REGISTER_MOD);
}


void RegisterDialog::slot_reg_mod_finish(ReqId id, ErrorCode err, QString res)
{
    if(err != ErrorCode::SUCCESS)
    {
        qDebug() << "slot_reg_mod_finish errorCode: " << err;
        _ShowTip(tr("网络请求错误"), false);
        return;
    }

    //解析 json
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    if(jsonDoc.isNull())
    {
        _ShowTip(tr("json 解析失败"), false);
        qDebug() << __FILE__ << ":" << __LINE__ << "  json 解析失败";
        return;
    }
    if(!jsonDoc.isObject())
    {
        _ShowTip(tr("json 解析错误"), false);
        qDebug() << __FILE__ << ":" << __LINE__ << "  json 解析错误";
        return;
    }

    //根据id回调指定的函数
    _handlers[id](jsonDoc.object());

    return;
}

//注册确认按钮槽函数
void RegisterDialog::on_confirm_btn_clicked()
{
    if(ui->user_edit->text() == ""){
        _ShowTip(tr("用户名不能为空"), false);
        return;
    }
    if(ui->email_edit->text() == ""){
        _ShowTip(tr("邮箱不能为空"), false);
        return;
    }
    if(ui->pass_edit->text() == ""){
        _ShowTip(tr("密码不能为空"), false);
        return;
    }
    if(ui->confirm_edit->text() == ""){
        _ShowTip(tr("确认密码不能为空"), false);
        return;
    }
    if(ui->confirm_edit->text() != ui->pass_edit->text()){
        _ShowTip(tr("密码和确认密码不匹配"), false);
        return;
    }
    if(ui->varify_edit->text() == ""){
        _ShowTip(tr("验证码不能为空"), false);
        return;
    }

    QJsonObject json_obj;
    json_obj["username"] = ui->user_edit->text();
    json_obj["email"] = ui->email_edit->text();
    json_obj["password"] = ui->pass_edit->text();
    json_obj["verificationCode"] = ui->varify_edit->text();
    MagicSingleton<HttpMgr>::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/user_register"),
                                        json_obj, ReqId::ID_REG_USER,Modules::REGISTER_MOD);
}

void RegisterDialog::_AddTipErr(TipErr code, QString msg)
{
    _error[code] = msg;
    _ShowTip(msg, false);
}
void RegisterDialog::_DelTipErr(TipErr code)
{
    _error.remove(code);
    if(_error.empty())
    {
        ui->error_tipe_label->clear();
        return;
    }

    _ShowTip(_error.first(), false);
}

void RegisterDialog::_CheckUserValid()
{
    if(ui->user_edit->text().isEmpty())
    {
        _AddTipErr(TipErr::TIP_USER_ERR, tr("用户不能为空"));
        return;
    }

    _DelTipErr(TipErr::TIP_USER_ERR);
}
void RegisterDialog::_CheckEmailValid()
{
    if(ui->email_edit->text().isEmpty())
    {
        _AddTipErr(TipErr::TIP_EMAIL_ERR, tr("邮箱不能为空"));
        return;
    }

    auto email = ui->email_edit->text();
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)(\.(\w+))+)");
    if(!regex.match(email).hasMatch())
    {
        _AddTipErr(TipErr::TIP_EMAIL_ERR, tr("邮箱格式不正确"));
        return;
    }

    _DelTipErr(TipErr::TIP_EMAIL_ERR);
}
void RegisterDialog::_CheckPassValid()
{
    if(ui->pass_edit->text().isEmpty())
    {
        _AddTipErr(TipErr::TIP_PWD_ERR, tr("密码不能为空"));
        return;
    }

    if(ui->pass_edit->text().size() < 6)
    {
        _AddTipErr(TipErr::TIP_PWD_ERR, tr("密码长度不能小于6位"));
        return;
    }

    _DelTipErr(TipErr::TIP_PWD_ERR);
}
void RegisterDialog::_CheckConfirmValid()
{
    if(ui->confirm_edit->text().isEmpty())
    {
        _AddTipErr(TipErr::TIP_CONFIRM_ERR, tr("确认密码不能为空"));
        return;
    }

    if(ui->pass_edit->text() != ui->confirm_edit->text())
    {
        _AddTipErr(TipErr::TIP_PWD_CONFIRM, tr("两次输入的密码不一致"));
        return;
    }
    _DelTipErr(TipErr::TIP_PWD_CONFIRM);
}
void RegisterDialog::_CheckVarifyValid()
{
    if(ui->varify_edit->text().isEmpty())
    {
        _AddTipErr(TipErr::TIP_VARIFY_ERR, tr("验证码不能为空"));
        return;
    }

    _DelTipErr(TipErr::TIP_VARIFY_ERR);
}


void RegisterDialog::_ChangeTipPage()
{
    _countdown_timer->stop();
    ui->stackedWidget->setCurrentWidget(ui->page_2);

    _countdown_timer->start(1000);
}

void RegisterDialog::on_back_btn_clicked()
{
    _countdown_timer->stop();
    //发送信号切换回登录界面
    emit sigSwitchLogin();
}


void RegisterDialog::on_cance_btn_clicked()
{
    emit sigSwitchLogin();
}

